package net.vsame.url2sql.helper;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

import net.vsame.url2sql.domain.Url2SqlContext;
import net.vsame.url2sql.web.bigpipe.BigpipeDataHelper;

public class JsHelper {
	
	
	private static Invocable jsFunction = null;
	private static ScriptEngine engine = null;
	
	static {
		resetJsInvocable();
	}
	
	/**
	 * 重新设置JS执行接口
	 */
	private static void resetFun(){
		if (engine instanceof Invocable) {
			jsFunction = (Invocable) engine;
		}else{
			throw new RuntimeException("not suppont!");
		}
	}
	
	/**
	 * 重新初始化</br>
	 * 注意：执行完该方法后扩展的脚本全部失效，需依次再执行evel方法
	 */
	public static void resetJsInvocable() {
		ScriptEngineManager manager = new ScriptEngineManager();
		engine  = manager.getEngineByName("JavaScript");
		Reader vsameReader = new InputStreamReader(JsHelper.class.getResourceAsStream("/core.js"));
		try {
			engine.eval(vsameReader);
		}catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				vsameReader.close();
			} catch (IOException e) {
			}
		}
		resetFun();
	}
	
	/**
	 * 增加扩展校验脚本
	 * @param script
	 */
	public static void eval(String script){
		try {
			engine.eval(script);
		} catch (ScriptException e) {
			throw new RuntimeException(e);
		}
		resetFun();
	}
	
	/**
	 * code!=0 表示拦截
	 * @return
	 */
	public static void execute(String js){
		Url2SqlContext context = WebHelper.getContext();
		try {
			jsFunction.invokeFunction("execute", js, context);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void main(String[] args) {
		execute("D.put404();");
		System.out.println(BigpipeDataHelper.getMap());
	}

}
